package com.ssyx.common.auth;

import com.alibaba.fastjson.JSON;
import com.ssyx.utils.JwtHelper;
import com.ssyx.vo.user.UserLoginVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName:UserLoginInterceptor
 * Description:
 * 会员登录拦截器
 * @Author kay
 * @Create 2024/5/15 10:47
 * @Version 1.0
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //从请求头中,得到token
        String token = request.getHeader("token");
        //根据token得到用户信息一般有2种方法
        ////1.当redis中,key为固定字符串+token,value为用户信息时,直接根据token获得用户信息,如下代码示例
        //String stringUserLoginVo = redisTemplate.opsForValue().get("user:ssyx:" + token);

        ////2.当token是userId + userName根据jwt生成,即通过token可以得到userId
        ////且redis中,key为固定字符串+userId,value为用户信息,可以根据如下代码得到用户信息
        Long userId = JwtHelper.getUserId(token);
        String stringUserLoginVo = redisTemplate.opsForValue().get("user:ssyx:" + userId);

        //将得到的json字符串转换成实体类
        UserLoginVo userLoginVo = JSON.parseObject(stringUserLoginVo, UserLoginVo.class);
        //放到threadLocal里面
        AuthContextHolder.setUserLoginVo(userLoginVo);
        return true;
    }
}
